<template>
  <div class="select-tooltip">
    <q-select class="select multipe-select margin-b-20"
              :multiple="multiple"
              outlined
              dense
              emit-value
              map-options
              options-dense
              ref="select"
              @input="selStation"
              :options="options"
              v-model="devicesData"
              style="margin-right: 20px">
      <q-tooltip v-if="multiple && devicesData && devicesData.length>0">
        <span v-for="(item,index) in devicesData"
              :key="index">
          <span>{{devicesLabel[item]}} </span>
        </span>
      </q-tooltip>
      <template v-slot:no-option>
        <div class="no-option" />
      </template>
      <template v-slot:before>
        <span class="form-name">{{msg}}:</span>
      </template>
    </q-select>
  </div>
</template>

<script>
export default {
  name: 'select-tooltip',
  props: {
    // 下拉选的值
    options: {
      type: Array,
      required: true
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 下拉选的标题
    msg: {
      type: String
    }
  },
  data () {
    return {
      devicesData: this.multiple ? [] : ''
    }
  },
  watch: {
    value: {
      handler (val) {
        this.devicesData = val
      },
      deep: true,
      immediate: true
    },
    devicesData: {
      deep: true,
      handler () {
        this.$emit('input', this.devicesData)
      }
    },
    options: {
      deep: true,
      handler () {
        this.devicesData = ['all']
      }
    }
  },
  computed: {
    devicesLabel () {
      const devicesLabel = {}
      this.options.forEach(item => {
        devicesLabel[item.value] = item.label
      })
      return devicesLabel
    }
  },
  methods: {
    // 选择工位触发
    selStation (val) {
      if (val[0] === 'all' && this.multiple && val.length > 1) {
        this.devicesData = this.devicesData.slice(1)
      }
      if (val.slice(1).indexOf('all') > -1 && this.multiple) {
        this.devicesData = ['all']
      }
    }
  },
  mounted () {
    // 多选的时候初始化
    if (this.multiple && this.devicesData !== []) {
      this.devicesData = ['all']
    }
  }
}
</script>

<style scoped lang="stylus"></style>
